using System.Collections;
using System.Reflection.Metadata;
using System.Runtime.InteropServices.Marshalling;
using System.Text;
using Dotnet.Script.ScriptPath;
using Markdig;
using Markdig.Syntax;

namespace Dotnet.Script.NutStore;

class NutStore
{
    public static void ConvertToListenText(string folderPath)
    {
        List<string> folderPaths = PathHandle.ListDirsNoSubdirectories(folderPath);
        // List<string> folderPaths = new List<string> { @"D:\NutStore\修行摘录" };

        var mergerFilePath = Path.Combine(PathHandle.SrcDirPath, "listen_total", "total.txt");

        using StreamWriter mergerWriter = new(mergerFilePath, false, Encoding.UTF8);

        foreach (var folder in folderPaths)
        {
            string folderName = Path.GetFileName(folder);
            // 过滤需要合并的文件夹
            if (
                folderName.StartsWith("listen")
                || folderName.StartsWith("bj_")
                || folderName.StartsWith("xx_")
                || folderName.StartsWith("zz_")
                || folderName.StartsWith("NutStore.Script")
            )
                continue;


            System.Console.WriteLine(folderName);

            mergerWriter.WriteLine($"\n下面是{folderName}的内容:\n");

            var filePath = Path.Combine(PathHandle.SrcDirPath, "listen", folderName + ".txt");

            using StreamWriter write = new(filePath, false, Encoding.UTF8);
            List<string> filePaths = PathHandle.ListFilesAndSubdirectoriesOrderedByLastModified(
                folder
            );

            foreach (var file in filePaths)
            {
                if (Path.GetExtension(file) != ".md")
                    continue;

                using StreamReader reader = new StreamReader(file);
                string? line;

                while ((line = reader.ReadLine()) != null)
                {
                    if (line.StartsWith("# "))
                    {
                        var newLine = $"\n[p5000]\n大标题：{line.Replace("# ", "")}\n[p2000]\n";
                        write.WriteLine(newLine);
                        mergerWriter.WriteLine(newLine);
                    }
                    else if (line.StartsWith("## "))
                    {
                        var newLine = $"\n[p2000]小标题：{line.Replace("## ", "")}\n[p1000]\n";
                        write.WriteLine(newLine);
                        mergerWriter.WriteLine(newLine);
                    }
                    else
                    {
                        write.WriteLine(line);
                        mergerWriter.WriteLine(line);
                    }
                }
            }
        }
    }
}
